function TreeNode(val, left, right) {
  this.val = (val === undefined ? 0 : val)
  this.left = (left === undefined ? null : left)
  this.right = (right === undefined ? null : right)
}

function createTree(arr) {
  if (arr.length < 1)
    return null;
  if (arr.length == 1)
    return new TreeNode(arr[0]);
  let NodeArr = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] == null) {
      NodeArr.push(null);
      continue;
    }
    let tempNode = new TreeNode(arr[i], null, null);
    NodeArr.push(tempNode);
  }
  for (let i = 0; i < arr.length; i++) {
    if (NodeArr[i] == null) continue;
    if (2 * i + 1 < arr.length)
      NodeArr[i].left = NodeArr[2 * i + 1];
    if (2 * i + 2 < arr.length)
      NodeArr[i].right = NodeArr[2 * i + 2];
  }
  return NodeArr[0];
}

function preShow(node) {
  if (node == null)
    return;
  console.log(node.val);
  preShow(node.left);
  preShow(node.right);
}

/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var inorderTraversal = function (root) {
  // root = createTree(root);
  let result = [];
  if (root == null) {
    return result;
  }
  let stack = [];
  while (stack.length || root != null) {
    // 当前节点有左子树，将左子节点放入stack
    while (root != null) {
      stack.push(root);
      root = root.left;
    }
    // 此时root已经是null，代表没有左子节点了，开始出栈
    root = stack[stack.length - 1];
    stack.splice(stack.length - 1, 1);
    // 处理当前节点
    result.push(root.val);
    // 处理右子节点
    root = root.right;
  }
  return result;
};
// let root = [1,null,2,3];
// console.log(inorderTraversal(root));
// root = [];
// console.log(inorderTraversal(root));
// root = [1];
// console.log(inorderTraversal(root));
let root = [1, null, 2, null, null, 3];
console.log(inorderTraversal(root));
root = [];
console.log(inorderTraversal(root));
root = [1];
console.log(inorderTraversal(root));
root = [1, null, 0, null, null, 3];
console.log(inorderTraversal(root));
